#define  _CRT_SECURE_NO_WARNINGS
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int dfs(TreeNode* root, int& k)
    {
        int ret = -1;
        if (root->left) ret = dfs(root->left, k);
        if (ret != -1) return ret;
        if (k-- == 1) ret = root->val;
        if (ret != -1) return ret;
        if (root->right) ret = dfs(root->right, k);
        return ret;
    }
public:
    int kthSmallest(TreeNode* root, int k) {
        return dfs(root, k);
    }
};